package com.mf.service.impl.basic;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mf.constant.ConstantPermission;
import com.mf.exception.GraceException;
import com.mf.mapper.basic.MapperUserRole;
import com.mf.service.basic.ServiceUserRole;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.mf.entity.dto.basic.DtoRole;
import com.mf.entity.req.basic.search.SearchReqRole;
import com.mf.mapper.basic.MapperRole;
import com.mf.service.basic.ServiceRole;

import java.util.List;


@Service
public class ImplServiceRole extends ServiceImpl<MapperRole, DtoRole> implements ServiceRole {
    @Resource
    private ServiceUserRole serviceUserRole;

    @Resource
    private MapperRole mapperRole;

    @Resource
    private MapperUserRole mapperUserRole;

    /**
     * 参数查询条件
     */
    @Override
    public LambdaQueryWrapper<DtoRole> fillParams(SearchReqRole params) {
        final LambdaQueryWrapper<DtoRole> wrapper = loadQw();
        if (StringUtils.isNotBlank(params.getKey())) {
            wrapper.and(w -> {
                w.like(DtoRole::getRoleName, params.getKey())
                        .or()
                        .like(DtoRole::getRemark, params.getKey());
            });
        }
        wrapper.orderByDesc(DtoRole::getId);
        return wrapper;
    }

    /**
     * 分页列表查询树结构
     */
    @Override
    public Page<DtoRole> findPageTreeByParams(SearchReqRole searchReqRole) {
        Page<Object> page = searchReqRole.getPage();
        page.addOrder(OrderItem.desc("id"));
        return mapperRole.findPageTreeByParams(page, searchReqRole);
    }

    /**
     * 删除
     */
    @Override
    public void deleteById(Integer id) {
        findCheckById(id, true);
        GraceException.display(serviceUserRole.countByRoleId(id) > 0, "当前角色有用户不可删除");
        GraceException.display(countByPid(id) > 0, "当前角色有子节点不可删除");
        removeById(id);
    }

    /**
     * 根据pid查询子数量
     */
    @Override
    public long countByPid(Integer id) {
        LambdaQueryWrapper<DtoRole> wr = loadQw();
        wr.eq(DtoRole::getPid, id);
        return count(wr);
    }

    /**
     * 根据用户id查询已关联角色
     */
    @Override
    public List<Integer> listByUserId(Integer userId) {
        // 管理员有所有的角色
        if (ConstantPermission.ADMIN_ID.equals(userId)) {
            return list().stream().map(DtoRole::getId).toList();
        }
        return mapperUserRole.listByUserId(userId);
    }
}